package net.zoneland.knowledge.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;

import net.zoneland.knowledge.constant.Constants;
import net.zoneland.knowledge.constant.ResponseMessage;
import net.zoneland.knowledge.constant.WebConstant;
import net.zoneland.knowledge.dao.UploadInfoMapper;
import net.zoneland.knowledge.model.EsQuestion;
import net.zoneland.knowledge.model.ResponseModel;
import net.zoneland.knowledge.model.ResponseResult;
import net.zoneland.knowledge.model.UploadInfo;
import net.zoneland.knowledge.service.DataManageService;
import net.zoneland.knowledge.utils.GsonUtils;

/**
 * 题库数据管理接口.
 *
 * @author: bcc
 * 2021/5/24
 */
@RestController
@RequestMapping("/datamanage")
public class DataManageController {
    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(DataManageController.class);

    /**
     * 数据查询接口.
     */
    @Autowired
    private DataManageService dataManageService;

    @Autowired
    private UploadInfoMapper uploadInfoMapper;
    /**
     * 批量插入、更新、删除数据.
     * @param list 数据
     * @return 结果
     * @throws Exception 异常
     */
    @PostMapping("/dealBatch")
    public ResponseModel dealBatch(@RequestBody List<EsQuestion> list) throws  Exception {
        final ResponseModel<?> responseModel = new ResponseModel<>();
        final List<String> checkInfo = checkEsQuestionList(list);
        if (CollectionUtils.isEmpty(checkInfo)) {
            final List<String> result = dataManageService.dealBatch(list);
            if (CollectionUtils.isNotEmpty(result)) {
                responseModel.setResult(WebConstant.RESULT_FAIL);
                responseModel.setMessage(result.stream().collect(Collectors.joining(";")));
            }
        } else {
            responseModel.setResult(WebConstant.RESULT_FAIL);
            responseModel.setMessage(checkInfo.stream().collect(Collectors.joining("|")));
        }
        return responseModel;
    }

    /**
     * 数据校验.
     * @param list 数据
     * @return 结果
     */
    private static List<String> checkEsQuestionList(final List<EsQuestion> list) {
        final List<String> rs = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            rs.add("参数不能为空");
            return rs;
        }
        int i = 0;
        boolean invalidFlag = false;
        for (EsQuestion esQuestion : list) {
            i++;
            final String checkInfo = checkEsQuestion(esQuestion);
            if (StringUtils.isNotBlank(checkInfo) || null == esQuestion) {
                rs.add("列表第" + i + "个参数不正确：" + checkInfo);
                invalidFlag = true;
            } else {
                // 参数不合规就不用执行下面的操作了
                if (invalidFlag) {
                    continue;
                }
                final List<String> dns = Arrays.stream(esQuestion.getTargetCompanyDn().split(Constants.STRING_SEMICOLON))
                                .filter(StringUtils::isNotBlank)
                                .collect(Collectors.toList());
                esQuestion.setFlag(dns);
            }

        }
        return rs;
    }

    /**
     * 单条数据校验.
     * @param esQuestion 数据
     * @return 结果
     */
    private static String checkEsQuestion(final EsQuestion esQuestion) {
        if (null == esQuestion) {
            return "题库对象不能为空";
        }
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isEmpty(esQuestion.getPk())) {
            sb.append("题库主键不能为空；");
        }
        if (esQuestion.getNum() == null) {
            sb.append("题库编号不能为空；");
        }
        if (null == esQuestion.getCategory()) {
            sb.append("题库类型来源不能为空；");
        }
        if (null == esQuestion.getOperation()) {
            sb.append("操作类型不正确;");
        }
        if (StringUtils.isEmpty(esQuestion.getLevel1Title())) {
            sb.append("一级科目不能为空;");
        }
        if (StringUtils.isEmpty(esQuestion.getQuestion())) {
            sb.append("问题题干不能为空;");
        }
        if (StringUtils.isEmpty(esQuestion.getAnswer())) {
            sb.append("问题答案不能为空;");
        }
        if (StringUtils.isEmpty(esQuestion.getTargetCompanyDn())) {
            sb.append("归属公司不能为空;");
        }
        return sb.toString();
    }

    /**
     * 处理单条数据.
     * @param esQuestion 数据
     * @return 结果
     * @throws Exception 异常
     */
    @PostMapping("/dealOne")
    public ResponseModel dealOne(@RequestBody final EsQuestion esQuestion) throws Exception {
        if (null != esQuestion) {
            return dealBatch(Lists.newArrayList(esQuestion));
        }

        final ResponseModel<?> responseModel = new ResponseModel<>();
        responseModel.setResult(WebConstant.RESULT_FAIL);
        responseModel.setMessage(ResponseMessage.REQUEST_PARAM_ERROR);
        return responseModel;
    }

    /**
     * 获取单条数据.
     * @param id esId
     * @return 结果
     */
    @PostMapping("/getById")
    public String getById(final String id) {
        final ResponseResult<EsQuestion> result = new ResponseResult<>();
        try {
            final EsQuestion eq = dataManageService.getById(id);
            result.setData(eq);
        } catch (Exception e) {
            result.setResult(ResponseResult.FAILED_RESULT);
            result.setMessage("getById fail！");
            LOGGER.error(">>>>>>>>>>>>>getById fail：", e);
        }
        return GsonUtils.toJson(result);
    }


    /**
     * 显示附件.
     * @param id 文件id
     * @param response http响应
     */
    @GetMapping("/showUpload")
    public void showUpload(final String id, final ServletResponse response) {
        if (StringUtils.isBlank(id)) {
            return;
        }
        final UploadInfo uploadInfo = uploadInfoMapper.selectByPrimaryKey(id);
        Optional.ofNullable(uploadInfo).ifPresent(info -> {
            try (InputStream inputStream = new ByteArrayInputStream(info.getContent())) {
                response.setContentType(info.getContentType());
                ServletOutputStream outputStream = response.getOutputStream();
                IOUtils.copy(inputStream, outputStream);
                outputStream.flush();
            } catch (IOException e) {
                LOGGER.error("showUpload error, id:{}", id, e);
            }
        });

    }

}
